#include "baseClass/Picture.h"
#include "stb_image.h"
#include<iostream>
#include <glad/glad.h>


Picture::Picture(const Picture& other)
{
    data = new uint8_t[other.width * other.height * other.channels];
    memcpy(data, other.data, other.width * other.height * other.channels);
    width = other.width;
    height = other.height;
    channels = other.channels;
    formtype = other.formtype;
}

Picture::Picture(Picture&& other) noexcept
{
 
    this->channels = other.channels;
    this->data = other.data;
    this->height = other.height;
    this->width = other.width;
    this->formtype = other.formtype;
}

Picture::Picture(const char *path)
{
    stbi_set_flip_vertically_on_load(false);
    
    data = stbi_load(path, &width, &height, &channels, 0);

    if (!data)
    {
        std::cout << "Failed to load pic" << std::endl;
    }
    if(channels == 3)
    {
        formtype = GL_RGB;
    }
    else if(channels == 4)
    {
        formtype = GL_RGBA;
    }
}
Picture Picture::SplitImage(int x1,int y1,int x2,int y2)
{
    Picture picture2;
    picture2.data = new uint8_t[this->width * this->height * this->channels];
    picture2.width = x2 - x1 + 1;
    picture2.height = y2 - y1 + 1;
    picture2.channels = this->channels;
    picture2.formtype = this->formtype;
    for (int x = x1; x <= x2; x++)
    {
        for (int y = y1; y <= y2; y++)
        {
            for (int c = 0; c < this->channels; c++)
            {
                picture2.data[(y - y1) * picture2.width * picture2.channels + 
                              (x - x1) * picture2.channels + c] = 
                              this->data[(y * this->width + x) * this->channels + c];
            }
        }
    }
    return picture2;
}

std::string Picture::to_string()
{
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            std::cout << "[";
            for (int c = 0; c < channels; c++)
            {
                std::cout << (int)data[(y * width + x) * channels + c] << " ";
            }
            std::cout << "] ";
        }
        std::cout << std::endl;
    }
    return "";
}
Picture::~Picture(){delete data;};


